# -*- coding: utf-8 -*-
from utils.guacamole import MyGuacamole
from utils.crypt_pwd import CryptPwd
from fort.models import FortServerUser


class GTelnetConsumer(MyGuacamole):
    def __init__(self, *args, **kwargs):
        super(GTelnetConsumer, self).__init__(*args, **kwargs)
        self.fort_user = FortServerUser.objects.get(id=self.scope['path'].split('/')[3])
        self.ip = self.fort_user.fort_server.server.IP
        self.port = self.fort_user.fort_server.port
        self.username = self.fort_user.fort_username
        self.password = CryptPwd().decrypt_pwd(self.fort_user.fort_password)
        self.coding = self.fort_user.get_fort_code_display()
        self.protocol = 'telnet'

    def connect(self):
        if self.scope["user"].is_anonymous:
            self.close(code=1007)
        else:
            self.accept('guacamole')
        self.client.handshake(protocol=self.protocol,
                              hostname=self.ip, port=self.port,
                              password=self.password,
                              username=self.username,
                              width=self.width,
                              height=self.height,
                              )
        self.send('0.,{0}.{1};'.format(len(self.group_name), self.group_name))
        self.guacamole_thread.setDaemon(True)
        self.guacamole_thread.start()
